var express = require('express');
var router = express.Router();

const multer = require('multer');
const fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  // res.render('index', { title: 'Express' });
  res.send({
    success: true
  })
});

// router.post('/upload', multer({dest: 'upload'}).single('file'), (req, res) => {
//   console.log(req.file);
//   res.send(req.file);
// })

router.post('/upload', multer({dest:'upload'}).array('file', 10), (req, res) => {
  const files = req.files
  const fileList = []
  for(var i in files){
    // console.log(i)    // i是数字索引，从0开始
    var file = files[i]
    // console.log(file)
    // console.log(file.path)
    fs.renameSync(file.path, `upload/${file.originalname}`)
    file.path = `upload/${file.originalname}`
    // console.log(file)
    // console.log(file.path)
    fileList.push(file)
  }
  res.send(fileList)
})

router.post('/test', multer({dest: 'excel'}).single('testexcel'), (req, res) => {
  console.log(req.file);
  fs.renameSync(req.file.path, `excel/${req.file.originalname}`)
  req.file.path = `excel/${req.file.originalname}`
  req.file.filename = req.file.originalname
  console.log(req.file)
  res.send(req.file);
})

router.get('/download', (req, res) => {
  req.query.filename ? res.download(`excel/${req.query.filename}`) : res.send({success:false})
})

module.exports = router;
